package org.serverct.finalfight.game.listener.player;

import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.scheduler.BukkitRunnable;
import org.serverct.finalfight.FinalFight;
import org.serverct.finalfight.game.GameManager;
import org.serverct.finalfight.game.gui.SpectatorTeleporter;
import org.serverct.finalfight.internal.game.basic.BasicGame;
import org.serverct.finalfight.internal.game.basic.GameState;
import org.serverct.finalfight.internal.info.SimpleInfoHandler;
import org.serverct.finalfight.stat.StatManager;

public class DeathListener implements Listener {
    @EventHandler
    public void onDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();
        BasicGame game = GameManager.getGame(player);
        if (game == null) {
            return;
        }
        game.players.get(player.getUniqueId()).isAlive = false;

        StatManager.stats.get(player.getUniqueId()).death();
        StatManager.stats.get(player.getUniqueId()).lose();

        if (player.getKiller() != null) {
            StatManager.stats.get(player.getKiller().getUniqueId()).kill();
        }

        player.setGameMode(GameMode.SPECTATOR);
        SimpleInfoHandler.sendMessage(player, true, "afterdeath");

        new BukkitRunnable() {
            @Override
            public void run() {
                if(game.state== GameState.RUNNING) {
                    PlayerInventory inv = player.getInventory();
                    inv.setItem(4, SpectatorTeleporter.menuItem);
                }
            }
        }.runTaskLater(FinalFight.plugin, 10L);
    }
}
